﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Core.Models;
using Microsoft.Web.Helpers;
using System.Web.Security;
using OliveLite.Core.Membership;

namespace Core.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            if ((bool)Session["IsValid"])
            {
                Guid DomainId = (Guid)Session["DomainId"];
                CoreEntities core = new CoreEntities();
                List<MainMenu> list = core.MainMenus.Where(m => (m.DomainId == DomainId && m.IsDroppedYN == "N")).OrderBy(m => m.Sequence).ThenBy(m => m.Name).ToList();
                if (list.Count > 0)
                {
                    Session["URL"] = list[0].URL.Substring(1);
                    return Redirect(list[0].URL.Substring(1));
                }
                return View();
            }
            return RedirectToAction("Setup");
        }

        public ActionResult About()
        {
            return View();
        }

        public ActionResult Admin()
        {
            List<ActionLink> links = new List<ActionLink>();
            if (UserPermissions.HasPermission("Can Create/Delete Domain") || UserPermissions.HasPermission("Can Modify Domain"))
            {
                ActionLink link = new ActionLink();
                link.LinkText = "Domain";
                link.ActionName = "Index";
                link.ControllerName = "Domain";
                link.Id = Guid.Empty;
                links.Add(link);
            }
            if (UserPermissions.HasPermission("Can Create/Delete Domain") || UserPermissions.HasPermission("Can Modify Domain"))
            {
                ActionLink link = new ActionLink();
                link.LinkText = "Theme";
                link.ActionName = "Index";
                link.ControllerName = "Theme";
                link.Id = Guid.Empty;
                links.Add(link);
            }
            if (UserPermissions.HasPermission("Can Administer BU"))
            {
                ActionLink link = new ActionLink();
                link.LinkText = "Business Unit";
                link.ActionName = "Index";
                link.ControllerName = "BusinessUnit";
                link.Id = Guid.Empty;
                links.Add(link);
            }
            if (UserPermissions.HasPermission("Can Modify Domain"))
            {
                ActionLink link = new ActionLink();
                link.LinkText = "Main Menu";
                link.ActionName = "Index";
                link.ControllerName = "MainMenu";
                link.Id = Guid.Empty;
                links.Add(link);
            }
            if (UserPermissions.HasPermission("Can Administer Tags"))
            {
                ActionLink link = new ActionLink();
                link.LinkText = "Tag Categories";
                link.ActionName = "Index";
                link.ControllerName = "TagCategory";
                link.Id = Guid.Empty;
                links.Add(link);
            }
            if (UserPermissions.HasPermission("Can Administer User"))
            {
                ActionLink link = new ActionLink();
                link.LinkText = "Users";
                link.ActionName = "Index";
                link.ControllerName = "User";
                link.Id = (Guid)Session["BusinessUnitId"];
                links.Add(link);
            }
            if (UserPermissions.HasPermission("Can Administer Files"))
            {
                ActionLink link = new ActionLink();
                link.LinkText = "File Manager";
                link.ActionName = "Index";
                link.ControllerName = "File";
                link.Id = (Guid)Session["BusinessUnitId"];
                links.Add(link);
            }
            if (UserPermissions.HasPermission("Can Create/Delete Domain") || UserPermissions.HasPermission("Can Modify Domain"))
            {
                ActionLink link = new ActionLink();
                link.LinkText = "Recreate Search Index";
                link.ActionName = "Reindex";
                link.ControllerName = "Setup";
                link.Id = Guid.Empty;
                links.Add(link);
            }

            Guid BUId = (Guid)Session["BusinessUnitId"];
            Core.Models.Plugin plugin;
            CoreEntities core = new CoreEntities();
            //List<Core.Models.Plugin> plugins = core.Plugins.Where(m => (m.AdminController != null && m.IsDroppedYN == "N")).OrderBy(m => m.Name).ToList();
            List<Core.Models.BusinessUnitPlugin> BUPlugins = core.BusinessUnitPlugins.Where(m => (m.BusinessUnitId == BUId && m.IsDroppedYN == "N")).ToList();
            //foreach (Core.Models.Plugin plugin in BUPlugins.)
            for(int i = 0;i < BUPlugins.Count;i++)
            {
                plugin = BUPlugins[i].Plugin;
                if (UserPermissions.HasPermission(plugin.AdminPermission) && plugin.IsDroppedYN == "N" && (!String.IsNullOrEmpty(plugin.AdminController)))
                {
                    ActionLink link = new ActionLink();
                    link.LinkText = plugin.Name;
                    link.ActionName = plugin.AdminAction;
                    link.ControllerName = plugin.AdminController;
                    link.Area = plugin.Area;
                    link.Id = Guid.Empty;
                    links.Add(link);
                }
            }
            return View(links);
        }

        public ActionResult Search(string s, int p = 1)
        {
            Core.Search.SearchResults results;
            if (!String.IsNullOrEmpty(s))
            {
                Core.Search.SearchEngine se = new Search.SearchEngine((Guid)Session["DomainId"]);
                results = se.Search(s,10,p,10);
            }
            else
            {
                results = new Core.Search.SearchResults();
            }
            return View(results);
        }

        public ActionResult Setup()
        {
            try
            {
                CoreEntities core = new CoreEntities();
                if (core.Domains.ToList().Count() <= 0)
                {

                    string email = "admin@admin.com";
                    string password = "password";
                    string SecurityQuestion = "Who are you?";
                    string SecurityAnswer = "admin";

                    // Create User Account & Activate
                    MembershipCreateStatus status;
                    Membership.CreateUser(email, password, email, SecurityQuestion, SecurityAnswer, true, out status);
                    ContactUser cu = core.ContactUsers.First(m => m.Contact.Email == email);
                    cu.Contact.FirstName = "Administrator";
                    //cu.Password = cu.SecurityAnswer;
                    cu.OpenIDUserName = email;
                    cu.IsDroppedYN = "N";
                    cu.IsApprovedYN = "Y";
                    cu.IsLockedOutYN = "N";
                    cu.LastActivityDT = DateTime.Now;
                    cu.LastPasswordChangedDT = DateTime.Now;
                    cu.Contact.Status = "A";
                    cu.Contact.EmailVerifiedYN = "N";

                    // Setup Domain

                    Domain domain = new Domain();
                    domain.DomainId = Guid.NewGuid();
                    domain.DomainName = Request.ServerVariables["HTTP_HOST"].ToString();
                    domain.SiteTitle = domain.DomainName;
                    domain.IsMultiBUYN = "N";
                    domain.SMTPAllowSendYN = "N";
                    domain.EnableSelfRegisterYN = "N";
                    domain.ThemeId = core.Themes.First(m => m.Name == "default").ThemeId;
                    domain.PrimaryBU = Guid.NewGuid();
                    domain.SubscriptionLevel = "F";
                    domain.IsDroppedYN = "N";
                    domain.CreateDT = DateTime.Now;
                    domain.CreatedById = Guid.Empty;
                    domain.CreatedByName = "Initial Setup";
                    domain.ModifiedDT = DateTime.Now;
                    domain.ModifiedById = Guid.Empty;
                    domain.ModifiedByName = "Initial Setup";
                    core.AddToDomains(domain);
                    core.SaveChanges();

                    // Setup Business Unit Address
                    Address addr = new Address();
                    addr.AddressId = Guid.NewGuid();
                    addr.Line1 = "Unkonown";
                    addr.City = "Unknown";
                    addr.State = "NN";
                    addr.PostalCode = "00000";
                    addr.Country = "Unknown";
                    core.AddToAddresses(addr);

                    // Setup the Business Unit
                    BusinessUnit bu = new BusinessUnit();
                    bu.BusinessUnitId = domain.PrimaryBU;
                    bu.DomainId = domain.DomainId;
                    bu.BusinessUnitName = domain.DomainName;
                    bu.Phone = "123-123-1234";
                    bu.Email = "admin@admin.com";
                    bu.MainAddressId = addr.AddressId;
                    bu.IsDroppedYN = "N";
                    bu.CreateDT = DateTime.Now;
                    bu.CreatedById = Guid.Empty;
                    bu.CreatedByName = "Initial Setup";
                    bu.ModifiedDT = DateTime.Now;
                    bu.ModifiedById = Guid.Empty;
                    bu.ModifiedByName = "Initial Setup";
                    core.AddToBusinessUnits(bu);

                    // Create User Account on BusinessUnit
                    User u = new User();
                    u.UserId = Guid.NewGuid();
                    u.ContactId = core.Contacts.First(m => m.Email == email).ContactId;
                    u.BusinessUnitId = bu.BusinessUnitId;
                    u.IsDroppedYN = "N";
                    u.CreateDT = DateTime.Now;
                    u.CreatedById = u.UserId;
                    u.CreatedByName = "Self Registered";
                    u.ModifiedDT = DateTime.Now;
                    u.ModifiedById = u.UserId;
                    u.ModifiedByName = "Self Registered";
                    core.AddToUsers(u);

                    // Authorize User Account for System Administration
                    Authorization auth = new Authorization();
                    auth.AuthorizationId = Guid.NewGuid();
                    auth.UserId = u.UserId;
                    auth.RoleId = core.Roles.First(m => m.Name == "System Administrator").RoleId;
                    auth.IsDroppedYN = "N";
                    auth.CreateDT = DateTime.Now;
                    auth.CreatedById = Guid.Empty;
                    auth.CreatedByName = "Initial Setup";
                    auth.ModifiedDT = DateTime.Now;
                    auth.ModifiedById = Guid.Empty;
                    auth.ModifiedByName = "Initial Setup";
                    core.AddToAuthorizations(auth);
                    core.SaveChanges();

                    return View("SetupDone");
                }
            }
            catch (Exception ex)
            {
                string strg = ex.InnerException.Message;
                strg = strg;
            }
            return View();
        }
    }
}
